package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.exception.AddressBookBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    //这棵梨树撒旦法发健身房啊书法大赛发的


    //sdafgasdkm asfasofadgasfdhgad

    @Override
    public Integer saveAddress(AddressBook addressBook) {
        if (addressBook.getIsDefault() == null) {
            addressBook.setIsDefault(0);
        }
        addressBook.setCreateTime(LocalDate.now());
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.saveAddress(addressBook);

    }

    @Override
    public List<AddressBook> seleteAddress() {
        AddressBook build = AddressBook.builder().userId(BaseContext.getCurrentId()).build();
        return addressBookMapper.seleteAddress(build);
    }

    @Override
    public AddressBook selectDefaultAddress() {
        AddressBook build = AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(1).build();
        List<AddressBook> list = addressBookMapper.seleteAddress(build);
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Integer updateDefaultAddress(Long id) {
        AddressBook build = AddressBook.builder().id(id).isDefault(1).build();
        AddressBook build1 = AddressBook.builder().userId(BaseContext.getCurrentId()).isDefault(0).build();
        addressBookMapper.updateAddress(build1);
        return addressBookMapper.updateAddress(build);
    }

    @Override
    public Integer updateAddress(AddressBook addressBook) {
        /*if (addressBook.getUserId()!= BaseContext.getCurrentId()) {
            throw new AddressBookBusinessException("当前用户无权限修改");
        }*/
        return addressBookMapper.updateAddress(addressBook);
    }

    @Override
    public AddressBook selectAddressById(Long id) {
        AddressBook build = AddressBook.builder().id(id).build();
        List<AddressBook> addressBooks = addressBookMapper.seleteAddress(build);
        return addressBooks.get(0);
    }

    @Override
    public Integer deleteAddressById(Long id) {
        return addressBookMapper.deleteAddressById(id);
    }

}
